<template>
  <el-form
    label-position="left"
    label-width="80px"
    :model="registerForm"
    :rules="rules"
    ref="registerForm"
    class="register-form"
  >
    <div style="padding: 10px">
      <span class="title">注册</span>
    </div>
    <router-link to="/login" class="login-link">登录</router-link>
    <el-form-item prop="username" label="用户名">
      <el-input
        type="text"
        v-model="registerForm.username"
        placeholder="请输入手机号或邮箱"
      ></el-input>
    </el-form-item>
    <el-form-item prop="password" label="密码">
      <el-input
        id="password"
        type="password"
        v-model="registerForm.password"
        placeholder="请输入密码"
        show-password
      >
      </el-input>
    </el-form-item>
    <el-form-item prop="nickname" label="昵称">
      <el-input
        type="text"
        v-model="registerForm.nickname"
        placeholder="请输入昵称"
      ></el-input>
    </el-form-item>
    <el-form-item prop="authCode" label="验证码">
      <el-input
        type="text"
        v-model="registerForm.authCode"
        placeholder="请输入验证码"
      >
        <el-button
          slot="append"
          @click="sendMsg(registerForm.username)"
          style="color: white; background-color: #85ce62; width: 110px"
          :disabled="hasSendAuthCode"
          >{{ !hasSendAuthCode ? "获取验证码" : authTime + "秒" }}</el-button
        >
      </el-input>
    </el-form-item>
    <el-button type="success" @click="registerSubmit" style="width: 100%"
      >注册</el-button
    >
  </el-form>
</template>
<script>
import { getAuthCode, isUsernameExist, isNicknameExist } from "@/api/login";
import { validateUsername, validatePassword, validateNickname } from "@/utils/validate";

export default {
  data() {
    var checkUsername = (rule, value, callback) => {
      if (!validateUsername(value)) {
        callback(new Error("请输入合理的手机号或邮箱"));
      } else {
        // 校验是否已存在该username
        isUsernameExist(value).then((res) => {
          if (res.data > 0) {
            // 已存在
            callback(new Error("该用户名已存在"));
          } else {
            callback();
          }
        }).catch(err => {
          callback();
        });
      }
    };
    var checkPassword = (rule, value, callback) => {
      if (!validatePassword(value)) {
        callback(new Error("请输入6-16位含字母和数字的密码"));
      } else {
        callback();
      }
    };
    var checkNickname = (rule, value, callback) => {
      if (!validateNickname(value)) {
        callback(new Error("昵称可由汉字、英文大小写字母、数字组成"));
      } else {
        isNicknameExist(value).then(res => {
          if(res.data > 0) {
            callback("该昵称已被使用");
          } else {
            callback();
          }
        }).catch(err => {
          callback();
        })
      }
    };
    var checkAuthCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("验证码不能为空"));
      } else {
        var authCodeReg = /^[0-9]{6}$/;
        if (!authCodeReg.test(value)) {
          callback(new Error("请输入六位数验证码"));
        } else {
          callback();
        }
      }
    };
    return {
      hasSendAuthCode: false,
      authTime: 60,
      registerForm: {
        username: "",
        password: "",
        nickname: "",
        authCode: "",
      },
      rules: {
        username: [
          { required: true, validator: checkUsername, trigger: "change" },
        ],
        password: [
          { required: true, validator: checkPassword, trigger: "change" },
        ],
        nickname: [
          { required: true, validator: checkNickname, trigger: "change" },
        ],
        authCode: [
          { required: true, validator: checkAuthCode, trigger: "change" },
        ],
      },
    };
  },
  methods: {
    /**
     * 动态显示authcode有效时间
     */
    authCodeCountDown() {
      if (this.authTimeTimer) {
        clearTimeout(this.authTimeTimer);
      }
      this.authTimeTimer = setTimeout(() => {
        this.authTime -= 1;
        if (this.authTime < 0) {
          this.hasSendAuthCode = false;
          clearTimeout(this.authTimeTimer);
        } else {
          this.authCodeCountDown();
        }
      }, 1000);
    },

    sendMsg(username) {
      this.$refs.registerForm.validateField("username", (usernameError) => {
        if (!usernameError) {
          // 请求获取验证码
          this.authTime = 60;
          this.hasSendAuthCode = true;
          // 开始倒计时
          this.authCodeCountDown();

          getAuthCode(username)
            .then((response) => {
              this.registerForm.authCode = response.data;
            })
            .catch((err) => {
              this.hasSendAuthCode = false;
            });
        }
      });
    },
    registerSubmit() {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          this.$emit("on-success-valid", {
            username: this.registerForm.username,
            password: this.registerForm.password,
            nickname: this.registerForm.nickname,
            authCode: this.registerForm.authCode,
          });
        }
      });
    },
  },
};
</script>
<style scoped>
.register-form {
  border-top: 7px solid #47cf73;
  width: 400px;
  margin: 0 auto;
  padding: 35px 35px 15px 35px;
  border-radius: 5px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  background-color: white;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  align-items: center;
  flex-direction: column;
}

.title {
  height: 56px;
  line-height: 56px;
  padding: 0;
  margin: 0 auto;
  text-align: center;
  font-size: 38px;
}

.login-link {
  padding-bottom: 20px;
}

.login-link:link {
  color: #3fd472;
}
.login-link:hover {
  color: skyblue;
}

.login-link:visited {
  color: #1f798f;
}

.el-input {
  width: 250px;
}

.authcode-btn {
  position: absolute;
  right: 1px;
  top: 1px;
}
</style>